import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class HttpClientTest1 {

    @Test
    public void test01() {
        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                // ConnectTimeout和SocketTimeout的区别：https://www.cnblogs.com/kendoziyu/p/java-socket-so_timeout.html
                .setConnectTimeout(1000, TimeUnit.SECONDS)
                .setSocketTimeout(1000, TimeUnit.SECONDS)
                .build();
        PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder.create()
                .setDefaultConnectionConfig(connectionConfig)
                ;
        HttpClientBuilder clientBuilder = HttpClients.custom()
                // https://stackoverflow.com/questions/68990038/apache-httpclient-keep-alive-strategy-for-active-connections
//                .setKeepAliveStrategy()
                ;
        try (HttpClientConnectionManager connectionManager = connectionManagerBuilder.build();
                CloseableHttpClient httpClient = clientBuilder.setConnectionManager(connectionManager).build()) {
            ClassicHttpRequest request = ClassicRequestBuilder.get("https://www.baidu.com").build();
            for (;;) {
                String resp = httpClient.execute(request, response -> EntityUtils.toString(response.getEntity()));
                System.out.println(resp);
                Thread.sleep(1000);
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void test02() {
        try (CloseableHttpClient aDefault = HttpClients.createDefault()) {

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
